package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.BottomSignDailog
import com.zat.mes.andrmes.customerview.adapter.BottomDialogAdapter
import com.zat.mes.andrmes.data.*
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.main.vm.BindMachineModel
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.vm.MachineDayCareModel
import com.zat.mes.andrmes.dofun.work.vm.MachineModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.*
import kotlinx.android.synthetic.main.activity_mac_check_add.*
import kotlinx.android.synthetic.main.activity_mac_day_care_add.*
import kotlinx.android.synthetic.main.layout_title.*
import kotlinx.android.synthetic.main.layout_title_right_text.view.*
import permissions.dispatcher.*
import java.util.*

@RuntimePermissions
class MacDayCareAddActivity : BaseActivity() {

    var qcModel: QcPlanViewModel? = null
    var machineDayCareModel: MachineDayCareModel? = null
    var macDayTypes: MutableList<ParantTypeItem>? = null
    var madModel: BindMachineModel? = null
    var mathineBean: MathineBean? = null
    var mAdapter: BottomDialogAdapter? = null
    var macCareDayBean: MachineCareDayBean?=null

    override fun init() {
        initView()
        initData()
    }

    private fun initData() {
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        val empId = loginResultBean.empid

        qcModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcModel?.getParantTypeData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it.containsKey("MACHINE_MAINTENANCE_DAY")) {
                macDayTypes = it.get("MACHINE_MAINTENANCE_DAY")
            }
        })
        qcModel?.loadParantTypeList("MACHINE_MAINTENANCE_DAY")
        madModel = ViewModelProvider(this).get(BindMachineModel::class.java)
        //扫码查机器
        madModel?.getMathine()?.observe(this, androidx.lifecycle.Observer {

                if (it == null) {
                    showToast("未查到相关机器")
                }
                mathineBean = it
                tvMacCareNo.text = "设备编码：" + mathineBean?.macNo
                //去查询是否有过新增，如果有则修改，如果没有则新增。
            machineDayCareModel?.getMachineCheck(mathineBean?.macNo,
                    DateUtil.formatDate(Date(), DateUtil.FORMAT_3),empId.toString())

        })
        mAdapter = BottomDialogAdapter(R.layout.item_dialog_bottom)
        rvMacCareAdd.layoutManager = LinearLayoutManager(this)
        rvMacCareAdd.adapter = mAdapter

        machineDayCareModel = ViewModelProvider(this).get(MachineDayCareModel::class.java)
        //新增返回
        machineDayCareModel?.getAddMachineData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            showToast(it)
            mathineBean = null
            tvMacCareNo.text = "设备编码"
            mAdapter?.selectList?.clear()
            mAdapter?.notifyDataSetChanged()
        })

        //查询
        machineDayCareModel?.getMachineData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            mAdapter?.setNewData(macDayTypes)
            mAdapter?.selectList?.clear()
            mAdapter?.notifyDataSetChanged()
            if (it==null || it.size<=0){
                btnAddCareMac.text = "新增"
            }else{
                macCareDayBean = it[0]
                try {

                    if(macCareDayBean?.overhead=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(0)!!)
                    }
                    if(macCareDayBean?.leftAndRightFeeders=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(1)!!)
                    }
                    if(macCareDayBean?.sideSpring=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(2)!!)
                    }
                    if(macCareDayBean?.headBrush=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(3)!!)
                    }
                    if(macCareDayBean?.railheadAndAfterbody=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(4)!!)
                    }

                    if(macCareDayBean?.aroundAndScissors=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(5)!!)
                    }
                    if(macCareDayBean?.machineAndSideCover=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(6)!!)
                    }
                    if(macCareDayBean?.glassCoverInOut=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(7)!!)
                    }
                    if(macCareDayBean?.waterAndOil=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(8)!!)
                    }
                    if(macCareDayBean?.settlerBed=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(9)!!)
                    }
                    mAdapter?.notifyDataSetChanged()
                    btnAddCareMac.text = "修改"
                }catch (e:java.lang.Exception){}

            }
        })
    }

    private fun initView() {
        setContentView(R.layout.activity_mac_day_care_add)
        tVtitle.text = "电机维护日保养"
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        val inflate = LayoutInflater.from(this).inflate(R.layout.layout_title_right_text, null)
        inflate.tvTitleRight.text = "日保养历史"
        rlRightComm.addView(inflate)
        rlRightComm.visibility = View.VISIBLE
        val layoutParams: RelativeLayout.LayoutParams =
            inflate.layoutParams as RelativeLayout.LayoutParams
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
        layoutParams.rightMargin = DisplayUtil.dip2px(this, 30f)
        rlRightComm.setOnClickListener {
            startActivity(Intent(this,MacDayCareActivity::class.java))
        }
        btnScanMacCareAdd.setOnClickListener {
            showCameraWithPermissionCheck()
        }




        btnAddCareMac.setOnClickListener {

            if (mathineBean == null) {
                showToast("请扫机器码")
                return@setOnClickListener
            }
            //提交
            if (btnAddCareMac.text == "新增") {
                val macDayBean = MachineCareDayBean()
                macDayBean.machineNo = mathineBean?.macNo
                macDayBean.workDay = DateUtil.formatDate(Date(), DateUtil.FORMAT_3)
                val selectList = mAdapter?.selectList
                for (c in selectList?.indices!!) {
                    when (selectList.get(c).paramenname) {
                        "overhead" -> macDayBean?.overhead = "1"
                        "leftAndRightFeeders" -> macDayBean?.leftAndRightFeeders = "1"
                        "sideSpring" -> macDayBean?.sideSpring = "1"
                        "headBrush" -> macDayBean?.headBrush = "1"
                        "railheadAndAfterbody" -> macDayBean?.railheadAndAfterbody = "1"
                        "aroundAndScissors" -> macDayBean?.aroundAndScissors = "1"
                        "machineAndSideCover" -> macDayBean?.machineAndSideCover = "1"
                        "glassCoverInOut" -> macDayBean?.glassCoverInOut = "1"
                        "waterAndOil" -> macDayBean?.waterAndOil = "1"
                        "settlerBed" -> macDayBean?.settlerBed = "1"
                    }
                }
                machineDayCareModel?.addMachineCheck(macDayBean)
            }else{
                //修改
                macCareDayBean?.overhead = "0"
                macCareDayBean?.leftAndRightFeeders = "0"
                macCareDayBean?.sideSpring = "0"
                macCareDayBean?.headBrush = "0"
                macCareDayBean?.railheadAndAfterbody = "0"
                macCareDayBean?.aroundAndScissors = "0"
                macCareDayBean?.machineAndSideCover = "0"
                macCareDayBean?.glassCoverInOut = "0"
                macCareDayBean?.waterAndOil = "0"
                macCareDayBean?.settlerBed = "0"
                val selectList = mAdapter?.selectList
                for (c in selectList?.indices!!) {
                    when (selectList.get(c).paramenname) {
                        "overhead" -> macCareDayBean?.overhead = "1"
                        "leftAndRightFeeders" -> macCareDayBean?.leftAndRightFeeders = "1"
                        "sideSpring" -> macCareDayBean?.sideSpring = "1"
                        "headBrush" -> macCareDayBean?.headBrush = "1"
                        "railheadAndAfterbody" -> macCareDayBean?.railheadAndAfterbody = "1"
                        "aroundAndScissors" -> macCareDayBean?.aroundAndScissors = "1"
                        "machineAndSideCover" -> macCareDayBean?.machineAndSideCover = "1"
                        "glassCoverInOut" -> macCareDayBean?.glassCoverInOut = "1"
                        "waterAndOil" -> macCareDayBean?.waterAndOil = "1"
                        "settlerBed" -> macCareDayBean?.settlerBed = "1"
                    }
                }
                machineDayCareModel?.upDateMachineCheck(macCareDayBean!!)
            }
            showLoading()
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查机器
            showLoading()
            madModel?.selectMacByQr(qrCode);

        }
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(Intent(this, QrScanActivity::class.java), 0)

        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }
}